<template>
  <view class="page">
    <view class="content" id="publicsentiment">
      <view class="main">
        <uv-form labelPosition="left" :model="formData" ref="form">
          <uv-form-item :label="$t('组织')" @click="popup1open">
            <view class="view_input">
              <view class="view_input_left">
                <text>{{ poiId }}</text>
              </view>
              <view class="view_input_right">
                <uv-icon name="arrow-right" size="12"></uv-icon>
              </view>
            </view>
          </uv-form-item>
        </uv-form>
        <view class="main-pingfen">
          <view class="main-pingfen-top">
            <uv-button
              :custom-style="miniButton"
              color="#748ee2"
              v-if="user?.tenant.setai"
              @click="
                navigateTo('/pages/publicsentiment/aiidentifycommentlabelcount')
              "
            >
              AI标签
            </uv-button>
          </view>
          <view class="main-pingfen-date">
            <view
              @click="dateacitve = 'd'"
              :class="dateacitve === 'd' ? 'active' : ''"
              >{{ $t("1日") }}</view
            >
            <view
              @click="dateacitve = 'w'"
              class="border"
              :class="dateacitve === 'w' ? 'active' : ''"
              >{{ $t("7日") }}
            </view>
            <view
              @click="dateacitve = 'm'"
              :class="dateacitve === 'm' ? 'active' : ''"
              >{{ $t("30日") }}</view
            >
            <view
              @click="dateacitve = 'month'"
              :class="dateacitve === 'month' ? 'active' : ''"
              >{{ $t("本月") }}</view
            >
          </view>
        </view>
        <red
          v-if="redid"
          :list="list"
          :id="redid"
          :change="change"
          :show="show"
        >
          <template #default="defaultProps">
            <view>
              <ec-canvas
                v-if="defaultProps.show"
                :id="defaultProps.id"
                :canvas-id="defaultProps.canvasId"
                :ec="defaultProps.ec"
              ></ec-canvas>
            </view>
          </template>
        </red>
        <Yellow
          v-if="yellowid"
          :list="list"
          :id="yellowid"
          :change="change"
          :show="show"
          :shopdata="shopdata"
          :_feedbackTime="_feedbackTime"
          :feedbackTime="feedbackTime"
        >
          <template #default="defaultProps">
            <ec-canvas
              v-if="defaultProps.show"
              :id="defaultProps.id"
              :canvas-id="defaultProps.canvasId"
              :ec="defaultProps.ec"
            ></ec-canvas>
          </template>
        </Yellow>
        <blue
          v-if="blueid"
          :list="list"
          :id="blueid"
          :change="change"
          :show="show"
          :shopdata="shopdata"
          :_feedbackTime="_feedbackTime"
          :feedbackTime="feedbackTime"
        >
          <template #default="defaultProps">
            <ec-canvas
              v-if="defaultProps.show"
              :id="defaultProps.id"
              :canvas-id="defaultProps.canvasId"
              :ec="defaultProps.ec"
            ></ec-canvas>
          </template>
        </blue>

        <Green
          v-if="greenid"
          :list="list"
          :id="greenid"
          :change="change"
          :show="show"
          :shopdata="shopdata"
          :_feedbackTime="_feedbackTime"
          :feedbackTime="feedbackTime"
        >
          <template #default="defaultProps">
            <ec-canvas
              v-if="defaultProps.show"
              :id="defaultProps.id"
              :canvas-id="defaultProps.canvasId"
              :ec="defaultProps.ec"
            ></ec-canvas>
          </template>
        </Green>
      </view>
    </view>
  </view>
  <uv-popup
    ref="popup1"
    mode="bottom"
    @change="(e: any) => pageshow = e.show"
    :safeAreaInsetBottom="false"
  >
    <view>
      <selectdept
        ref="Deptref"
        v-model="formData.dep_id"
        @close="select"
        multiple
      >
      </selectdept>
    </view>
  </uv-popup>
</template>

<script setup lang="ts">
import { assign, head, isArray, last, orderBy } from "lodash-es";
import { computed, reactive, ref, watch, inject } from "vue";
import selectdept from "@/components/dept/selectdept.vue";
import { useI18n } from "vue-i18n";
import dayjs from "dayjs";
import api from "@/api";
import { onLoad, onShow } from "@dcloudio/uni-app";
import red from "./red.vue";
import blue from "./blue.vue";
import Yellow from "./yellow.vue";
import Green from "./green.vue";
import { navigateTo } from "@/util/navigator";
import { miniButton } from "@/util/style";
import { findLeafByLabel } from "@/util";

const $t = useI18n().t;

const pageshow = ref(false);
const list = ref<Eps.identifylabelEntity[]>([]);
const identifylabel = ref<Eps.identifylabelEntity[]>([]);
const formData = reactive({
  dep_id: [],
  feedbackTime: [
    dayjs().subtract(1, "day").format("YYYY-MM-DD HH:mm:ss"),
    dayjs().format("YYYY-MM-DD HH:mm:ss"),
  ],
  identifycommentlabels: [],
});

const Deptref = ref();
const user = inject<any>("user");
const poiId = computed(() => {
  if (formData.dep_id.length === 1) {
    return Deptref.value?.list.find(
      (c: Eps.DeptEntity) => c.id === formData.dep_id[0]
    )?.name;
  } else if (formData.dep_id.length === 0) {
    return "所有组织";
  } else {
    return `已筛选：${formData.dep_id.length}个组织`;
  }
});
const popup1 = ref();

function popup1open() {
  popup1.value.open();
}

const redid = computed(() => {
  return identifylabel.value.find((c) => c.remark === "红卡" && !c.parentId)
    ?.id;
});

const blueid = computed(() => {
  return identifylabel.value.find((c) => c.remark === "蓝卡" && !c.parentId)
    ?.id;
});

const greenid = computed(() => {
  return identifylabel.value.find((c) => c.remark === "绿卡" && !c.parentId)
    ?.id;
});

const yellowid = computed(() => {
  return identifylabel.value.find((c) => c.remark === "黄卡" && !c.parentId)
    ?.id;
});

const dateacitve = ref<string>("m");

const identifycommentlabelcount = ref<
  { identifylabelid: string; count: string; release: "N" | "O" }[]
>([]);

const feedbackTime = computed(() => {
  let feedbackTime = [
    dayjs().subtract(1, "day").format("YYYY-MM-DD"),
    dayjs().format("YYYY-MM-DD"),
  ];
  if (dateacitve.value === "d") {
    feedbackTime = [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")];
  }
  if (dateacitve.value === "w") {
    feedbackTime = [
      dayjs().subtract(1, "week").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ];
  } else if (dateacitve.value === "month") {
    feedbackTime = [
      dayjs().startOf("month").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ];
  } else {
    feedbackTime = [
      dayjs().subtract(30, "day").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ];
  }
  return feedbackTime;
});

const _feedbackTime = computed(() => {
  let feedbackTime = [
    dayjs().subtract(2, "day").format("YYYY-MM-DD"),
    dayjs().format("YYYY-MM-DD"),
  ];
  if (dateacitve.value === "d") {
    feedbackTime = [
      dayjs().subtract(1, "day").format("YYYY-MM-DD"),
      dayjs().subtract(1, "day").format("YYYY-MM-DD"),
    ];
  } else if (dateacitve.value === "w") {
    feedbackTime = [
      dayjs().subtract(2, "week").format("YYYY-MM-DD"),
      dayjs().subtract(1, "week").subtract(1, "day").format("YYYY-MM-DD"),
    ];
  } else if (dateacitve.value === "month") {
    feedbackTime = [
      dayjs()
        .subtract(1, "month")
        .startOf("month")
        .format("YYYY-MM-DD HH:mm:ss"),
      dayjs().subtract(1, "month").endOf("day").format("YYYY-MM-DD HH:mm:ss"),
    ];
  } else {
    feedbackTime = [
      dayjs().subtract(60, "day").format("YYYY-MM-DD"),
      dayjs().subtract(31, "day").format("YYYY-MM-DD"),
    ];
  }
  return feedbackTime;
});
interface Idata {
  dept_id: string;
  name: string;
  count: string;
  release: string;
  Ocount: string;
  identifylabelid: string;
}
const shopdata = ref<Idata[]>([]);
const show = ref(false);
async function select() {
  popup1.value?.close();
  show.value = false;
  const n = await api<any[]>(
    "/wechat/identifycomment/identifycommentlabelcount",
    { dep_id: formData.dep_id, feedbackTime: feedbackTime.value }
  );
  identifycommentlabelcount.value = [];
  n.forEach((c) => {
    identifycommentlabelcount.value.push(assign(c, { release: "N" }));
  });
  let _shopdata = await api<any[]>("/wechat/identifycomment/getshoplabel", {
    dep_id: formData.dep_id,
    feedbackTime: feedbackTime.value,
  });
  shopdata.value = _shopdata.map((c: Idata) => {
    return assign(c, { release: "当前周期", Ocount: 0 });
  });
  const f = await api<any[]>(
    "/wechat/identifycomment/identifycommentlabelcount",
    { dep_id: formData.dep_id, feedbackTime: _feedbackTime.value }
  );
  await api<any[]>("/wechat/identifycomment/getshoplabel", {
    dep_id: formData.dep_id,
    feedbackTime: _feedbackTime.value,
  }).then((f) => {
    f.forEach((c) => {
      const n = shopdata.value.find(
        (z) =>
          String(z.identifylabelid) === c.identifylabelid &&
          z.dept_id === c.dept_id
      );
      if (n) {
        n.Ocount = c.count;
      } else {
        shopdata.value.push(
          assign(c, { release: "上期周期", Ocount: c.count, count: 0 })
        );
      }
    });
  });
  f.forEach((c) => {
    identifycommentlabelcount.value.push(assign(c, { release: "O" }));
  });

  show.value = true;
}

/**
 *
 * @param identifycommentlabels
 * @param p 返回的父级层级
 * @param d 返回的子集层级
 */
function change(identifycommentlabels: string[], p = 0, d = 0) {
  const line = identifycommentlabels.map((e) => {
    return list.value.find((c) => String(c.id) == e);
  });
  // 父级
  const mapline: {
    count: number;
    data: {
      index: number;
      name: string;
      id: string;
      value: number;
      release: "N" | "O";
    }[]; // 子集
    id: string;
    index: number;
    name: string;
    parentId: number;
    color: string;
    Nvalue: number;
    Ovalue: number;
  }[] = [];
  line.forEach((e) => {
    const Ncount = Number(
      identifycommentlabelcount.value.find(
        (c) => c.identifylabelid == String(e?.id) && c.release === "N"
      )?.count || 0
    );
    const Ocount = Number(
      identifycommentlabelcount.value.find(
        (c) => c.identifylabelid == String(e?.id) && c.release === "O"
      )?.count || 0
    );
    // 父级
    let p1 = e;
    if (p) {
      for (const e in Array.from({ length: p })) {
        p1 = list.value.find((c) => String(c.id) == String(p1?.parentId));
      }
    }
    // 子集
    let c2 = e;
    if (d) {
      for (const e in Array.from({ length: d })) {
        c2 = list.value.find((c) => String(c.id) == String(c2?.parentId));
      }
    }
    const n = mapline.find((c) => String(c.id) == String(p1?.id));
    if (n) {
      n.count = n.count + 1;
      n.Nvalue = n.Nvalue + Ncount;
      n.Ovalue = n.Ovalue + Ocount;
      const Ndata = n.data.find(
        (c) => c.id === String(c2?.id) && c.release === "N"
      );
      const Odata = n.data.find(
        (c) => c.id === String(c2?.id) && c.release === "O"
      );
      if (Ndata) {
        Ndata.value = Ndata.value + Ncount;
      } else {
        n.data.push({
          id: String(c2?.id),
          index: Number(c2?.orderNum),
          name: String(c2?.name),
          value: Ncount,
          release: "N",
        });
      }
      if (Odata) {
        Odata.value = Odata.value + Ncount;
      } else {
        n.data.push({
          id: String(c2?.id),
          index: Number(c2?.orderNum),
          name: String(c2?.name),
          value: Ocount,
          release: "O",
        });
      }
    } else {
      const f = list.value.find((c) => String(c.id) == String(p1?.id));
      mapline.push({
        count: 1,
        data: [
          {
            id: String(c2?.id),
            index: Number(c2?.orderNum),
            name: String(c2?.name),
            value: Ncount,
            release: "N",
          },
          {
            id: String(c2?.id),
            index: Number(c2?.orderNum),
            name: String(c2?.name),
            value: Ocount,
            release: "O",
          },
        ],
        id: String(f?.id),
        index: Number(f?.orderNum || 0),
        name: String(f?.name),
        parentId: Number(e?.parentId),
        color: "#000",
        Nvalue: Ncount,
        Ovalue: Ocount,
      });
    }
  });
  let t = $t("今日");
  if (dateacitve.value === "d") {
    t = $t("今日");
  } else if (dateacitve.value === "w") {
    t = $t("本周");
  } else {
    t = $t("本月");
  }
  let t1 = $t("昨日");
  if (dateacitve.value === "d") {
    t1 = $t("昨日");
  } else if (dateacitve.value === "w") {
    t1 = $t("上周");
  } else {
    t1 = $t("上月");
  }
  const order = mapline.sort((a, b) => a.index - b.index);

  const data = order
    .map((c) =>
      c.data
        .map((z) => assign(z, { color: c.color }))
        .sort((a, b) => a.index - b.index)
    )
    .flat(999)
    .filter((e) => e.release === "N")
    .map((c) => {
      return {
        value: Number(c.value),
        type: t,
        date: c.id,
        name: c.name,
        color: c.color,
      };
    });
  const data2 = order
    .map((c) =>
      c.data
        .map((z) => assign(z, { color: c.color }))
        .sort((a, b) => a.index - b.index)
    )
    .flat(999)
    .filter((e) => e.release === "O")
    .map((c) => {
      return {
        value: Number(c.value),
        type: t1,
        date: c.id,
        name: c.name,
        color: c.color,
      };
    });

  return {
    xAxisdata: data.map((e) => e.date),
    name: [t, t1],
    series: [data, data2],
    data: data.concat(...data2),
    parent: order
      .map((c) => {
        return {
          count: c.count,
          name: c.name,
          id1: head(c.data)?.id,
          id2: last(c.data)?.id,
          value: c.Nvalue,
        };
      })
      .filter((e) => e.id1 && e.id2),
    parent2: order
      .map((c) => {
        return {
          count: c.count,
          name: c.name,
          id1: head(c.data)?.id,
          id2: last(c.data)?.id,
          value: c.Ovalue,
        };
      })
      .filter((e) => e.id1 && e.id2),
  };
}

onLoad(() => {
  api<Eps.identifylabelEntity[]>("/wechat/identifylabel/list")
    .then((res) => {
      list.value = res;
      // 渲染数据
      identifylabel.value = deepTree(list.value);
      select();
    })
    .catch((f) => {
      uni.showToast({
        icon: "error",
        title: f,
        duration: 2000,
      });
    });
});

watch(
  () => dateacitve.value,
  () => {
    select();
  }
);

function deepTree(list: any[], order?: "asc" | "desc"): any[] {
  const newList: any[] = [];
  const map: any = {};
  list.forEach((e) => (map[e.id] = e));

  list.forEach((e) => {
    const parent = map[e.parentId];

    if (parent) {
      (parent.children || (parent.children = [])).push(e);
    } else {
      newList.push(e);
    }
  });

  const fn = (list: Array<any>) => {
    list.map((e) => {
      if (isArray(e.children)) {
        e.children = orderBy(e.children, "orderNum", order);
        fn(e.children);
      }
    });
  };

  fn(newList);

  return orderBy(newList, "orderNum", order);
}

wx.showShareMenu({
  withShareTicket: true,
});
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 100vw;
}
</style>

<style lang="scss">
#publicsentiment {
  .main {
    margin-top: -36px;
    display: flex;
    flex: 1;
    padding-top: 72rpx;
    padding-left: 32rpx;
    padding-right: 32rpx;
    flex-direction: column;
    background-color: #fff;
    overflow: hidden;
    border-top-left-radius: 48rpx;
    border-top-right-radius: 48rpx;

    .content_form {
      width: calc(100vw - 48rpx);
      padding-left: 24rpx;
      padding-right: 24rpx;
      overflow: hidden;
      background-color: $uni-text-color-inverse;
    }

    .view_input {
      display: flex;
      flex-wrap: wrap;
      flex-shrink: 0;
      flex-grow: 0;
      flex-basis: auto;
      align-items: stretch;
      align-content: flex-start;

      .view_input_left {
        flex: 1;
        overflow: hidden;
        padding-right: 12rpx;
        height: 20px;
        font-size: 15px;
      }

      .view_input_right {
        width: 40rpx;
      }
    }

    .main-header {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;
      font-weight: 600;
      margin-bottom: 24rpx;
    }

    .main-pingfen {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 24rpx;
      justify-content: space-between;
      gap: 12rpx;

      .identifylabelids-button {
        display: flex;
        flex-wrap: wrap;
        gap: 12rpx;

        .identifylabelids-button-item {
          flex: none;
        }
      }
    }

    .main-pingfen-top {
      display: flex;
      flex-wrap: wrap;
      height: 64rpx;
      align-items: center;
      overflow: hidden;
      text-overflow: ellipsis; //溢出用省略号显示
      white-space: nowrap; //溢出不换行
      font-size: 28rpx;
      width: 400rpx;
    }

    .main-pingfen-top-1 {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;
    }

    .main-pingfen-top-2 {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;
      margin-left: 40rpx;
    }

    .main-pingfen-date {
      display: flex;
      flex-wrap: wrap;
      border-radius: 24rpx;
      background: linear-gradient(to bottom, #eeeeee, #d8d8d8);
      border: 1rpx solid rgba(200, 200, 200, 1);
      overflow: hidden;

      view {
        width: 64rpx;
        height: 64rpx;
        font-size: 24rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .active {
        color: #fff;
        background-color: #fd754c;
      }

      .border {
        border-left: 1rpx solid rgba(200, 200, 200, 1);
        border-right: 1rpx solid rgba(200, 200, 200, 1);
      }
    }

    .container {
      width: calc(100vw - 64rpx);
      height: 620rpx;

      view {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
